var BuyDialog = require("../dialog/dialog.js");
var app = getApp();
var goodsid;
var commentOffset = 0;
var WxParse = require('../../../wxParse/wxParse.js');
var hasArticle,isFirst;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailLoaded:false,
    swiperhgt: 0,
    total_banner: 0,
    current_banner: 0,
    mainshow: 1,
    detailsinfo: [],
    comments: [],
    comments_reply: {},
    discountShow: false,
    scrollView: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.ruid){
      app.globalData.ruid = options.ruid;
    }
    if(!options.goodsid){
      wx.switchTab({
        url: '/pages/newindex/newindex',
      });
      return;
    }
    goodsid = options.goodsid;
    var that = this;
    that.setData({
      goods_id: goodsid
    });
    hasArticle = false;
    isFirst = true;
    wx.getSystemInfo({
      success: function (res) {
        var hgt = 525 * res.windowWidth / 800;
        that.setData({
          swiperhgt: hgt,
          scrollHgt: res.windowHeight
        });
      },
    });

    BuyDialog.dialogInit(this, this.goBuyAction, this.addBuycarAction);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      dialogshow: false
    });
    if(isFirst){
      isFirst = false;
      app.showLoading();
    }
    app.ready(() => {
      app.sendRuid();
      this.loadDetail();
      commentOffset = 0;
      this.loadComments(commentOffset);
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.cancelCountdown();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // WxParse.emojisInit('[]', "/wxParse/emojis/", {});
    this.cancelCountdown();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var pathUrl = '/pages/store/goodsdetail/goodsdetail?ruid=' + app.globalData.uid + '&goodsid=' + goodsid;
    return {
      title: this.data.detailsinfo.name, // 转发后 所显示的title
      path: pathUrl, // 相对的路径
      success: (res) => { 
      },
      fail: function (res) {
        // 分享失败
        console.log(res)
      }
    }
  },
  loadDetail: function () {
    var url = '/index.php/api/Goods/goodsInfo';
    var params = {
      id: goodsid,
      uid: '0'
    };
    app.request(url,params).then(this.detailCallBack.bind(this));
  },
  detailCallBack: function (result=null) {
    if(result.status != 'ok'){
      return;
    }
    result = result.result;
    var detailsinfo = {};
    detailsinfo.banners = result.imgarr;
    for (var i = 0; i < detailsinfo.banners.length; i++) {
      detailsinfo.banners[i].image_url = app.globalData.webUrl + detailsinfo.banners[i].image_url;
    }
    detailsinfo.name = result.arr.goods_name;
    detailsinfo.oprice = result.arr.market_price;
    detailsinfo.dprice = result.arr.shop_price;
    detailsinfo.storage = result.arr.store_count;
    detailsinfo.sales = Math.abs(parseInt(result.arr.sales_sum));
    detailsinfo.iconurl = app.globalData.webUrl + result.arr.original_img;
    detailsinfo.attrlist = result.attrlist;
    detailsinfo.spec_price = result.spec_goods_price;

    if(!hasArticle){
      hasArticle = true;
      var article = app.repicSrc(result.arr.goods_content);
      article = article.replace(/&nbsp;/g, '');
      article = article.replace(/amp;/g, '');
      WxParse.wxParse('article', 'html', article, this, 0);
    }

    var spec_filters = result.filter_spec;
    var standards = [];
    for (var specKey in spec_filters) {
      var specinfo = {};
      specinfo.name = specKey;
      specinfo.vals = [];
      specinfo.keys = [];
      specinfo.pics = [];
      for (var i = 0; i < spec_filters[specKey].length; i++) {
        specinfo.vals.push(spec_filters[specKey][i].item);
        specinfo.keys.push(spec_filters[specKey][i].item_id);
        spec_filters[specKey][i].src = app.globalData.webUrl + spec_filters[specKey][i].src;
        specinfo.pics.push(spec_filters[specKey][i].src);
      }
      specinfo.selected = '';
      specinfo.selectedkey = '';
      standards.push(specinfo);
    }

    var shortname = detailsinfo.name;
    if (shortname.length > 24) {
      shortname = shortname.substr(0, 24) + "...";
    }
    /* 初始化会话框 */
    var dialog = {
      name: shortname,
      price: detailsinfo.dprice,
      iconurl: detailsinfo.iconurl,
      storage: detailsinfo.storage,
      sales: detailsinfo.sales,
      standardtypes: standards
    };

    this.setData({
      detailsinfo: detailsinfo,
      dialogdata: dialog,
      current_banner: 1,
      total_banner: detailsinfo.banners.length,
      detailLoaded:true
    });

    if (result.spec_goods_price.length <= 0){
      var url = '/api/Goods/activity';
      var params = {
        goods_id: this.data.goods_id,
        item_id: 0,
        goods_num: 1,
      }
      getApp().request(url, params).then(res => {
        if (res.result && res.result.activity_is_on == 1) {          
          detailsinfo.oprice = detailsinfo.dprice;
          detailsinfo.dprice = res.result.shop_price;
          dialog.price = res.result.shop_price;
          this.Countown(res.result.start_time, res.result.end_time);
        }
        else {
          this.cancelCountdown();
        }
        this.setData({
          detailsinfo: detailsinfo,
          dialogdata: dialog
        });
      });
    }
    
    app.hideLoading();
  },
  //  dialog 事件转发
  standardSelectedTap: BuyDialog.standardSelected,
  changeBuyCount: BuyDialog.changeBuyCount,
  numInputCheck: BuyDialog.numInputCheck,
  closeDialog: BuyDialog.hide,
  buy_addcar_tap: BuyDialog.buyOrAddCar,
  cancelCountdown: BuyDialog.cancelCountdown,
  Countown: BuyDialog.Countown,
  //  dialog 空白事件
  doNothing: function () { },

  //  加载评论
  loadComments: function (offset) {
    var url = '/index.php/api/Goods/comment';
    var params = {
      goods_id: goodsid,
      commentType: 1,
      page: offset
    };
    app.request(url,params).then(this.commentCallBack.bind(this));
  },
  //  more comments
  loadMoreComments: function () {
    commentOffset++;
    this.loadComments(commentOffset)
  },
  // 评论回调
  commentCallBack: function (result) {
    result = result.result;
    var comments = result.arr;
    if (comments.length <= 0) {
      this.setData({
        commentHasMore: false
      });
      return;
    }
    var comments_reply = result.replyList;
    var cur_comments_reply = this.data.comments_reply;
    for (var keystr in comments_reply) {
      cur_comments_reply[keystr] = comments_reply[keystr];
      try {
        for (var i = 0; i < cur_comments_reply[keystr].length; i++) {
          cur_comments_reply[keystr][i].add_time = app.formatDateTime(cur_comments_reply[keystr][i].add_time);
        }
      }
      catch (exception) {

      }
    }
    var cur_comments = [];
    if(commentOffset > 0){
      cur_comments = this.data.comments;
    }
    for (var i = 0; i < comments.length; i++) {
      if (comments[i].img) {
        for (var j = 0; j < comments[i].img.length; j++) {
          comments[i].img[j] = app.globalData.webUrl + comments[i].img[j];
        }
      }
      comments[i].add_time = app.formatDateTime(comments[i].add_time);
      cur_comments.push(comments[i]);
    }
    var hasMoreCmm = true;
    if (cur_comments.length < 5) {
      hasMoreCmm = false;
    }
    this.setData({
      commentHasMore: hasMoreCmm,
      comments: cur_comments,
      comments_reply: cur_comments_reply
    });
    // console.log(this.data.comments);
  },
  // 
  swiperChange: function (event) {
    var curindex = event.detail.current;
    curindex += 1;
    this.setData({
      current_banner: curindex
    });
  },
  changeMainShow: function (event) {
    var show = parseInt(event.currentTarget.dataset.show);

    if (this.data.mainshow == show) {
      return;
    }
    var scrollView = '';
    if(show == 1){
      scrollView = 'content';
    }
    else if(show == 2){
      scrollView = 'comments';
    }
    else if(show == 3){
      scrollView = 'attrs';
    }
    
    this.setData({
      mainshow: show,
      scrollView: scrollView
    });
    
  },
  //  立即购买对话框
  to_buy_dialog: function () {
    BuyDialog.show(1);
  },
  //  加入购物车对话框
  to_car_dialog: function () {
    BuyDialog.show(2);
  },
  //  客服
  makePhoneCall: function () {
    // wx.makePhoneCall({
    //   phoneNumber: '021-10086',
    // });
  },
  //  去购物车
  toBuyCar: function () {
    console.log('aaaa');
    wx.switchTab({
      url: '/pages/my/car/car',
    });
  },
  goBuyAction: function () {
    var standardtypes = this.data['dialogdata'].standardtypes;
    var selected_standardtypes = [];
    if (standardtypes.length > 0) {
      var infocheck = true;
      for (var i = 0; i < standardtypes.length; i++) {
        if (standardtypes[i].selectedkey == '') {
          infocheck = false;
          break;
        }
      }
      if (infocheck == true) {
        for (var i = 0; i < standardtypes.length; i++) {
          selected_standardtypes.push(standardtypes[i].selectedkey);
        }
      }
      else {
        wx.showToast({
          image: '../../imgs/tips.png',
          title: '请选择产品规格',
        });
        return;
      }
    }
    selected_standardtypes.reverse();
    selected_standardtypes.sort(app.compare);
    var itemid = selected_standardtypes.join('_');
    if (itemid != '') {
      itemid = this.data.detailsinfo.spec_price[itemid].item_id;
    }
    var url = '/index.php/api/Cart/cart2';
    var params = {
      goods_id: goodsid,
      item_id: itemid,
      goods_num: this.data.buycount,
      action: 'buy_now'
    };
    app.showLoading();
    app.request(url,params).then(this.goBuyCallBack.bind(this));
  },
  goBuyCallBack: function (res) {
    // console.log(res);
    app.hideLoading();
    if (res.status == 'ok') {
      for (var i = 0; i < res.result.cartList.length; i++) {
        res.result.cartList[i].goods.goods_content = '';
      }
      var orderinfos = JSON.stringify(res.result);
      wx.navigateTo({
        url: '../../orderlist/neworder/neworder?orderinfos=' + orderinfos + '&action=buy_now',
      });
    }
    else {
      wx.showToast({
        icon: 'none',
        title: res.msg,
      });
    }
  },
  ///////-------------------------以下--------------------加入购物车---------------
  addBuycarAction: function () {
    var standardtypes = this.data['dialogdata'].standardtypes;
    var selected_standardtypes = [];
    if (standardtypes.length > 0) {
      var infocheck = true;
      for (var i = 0; i < standardtypes.length; i++) {
        if (standardtypes[i].selectedkey == '') {
          infocheck = false;
          break;
        }
      }
      if (infocheck == true) {
        for (var i = 0; i < standardtypes.length; i++) {
          selected_standardtypes.push(standardtypes[i].selectedkey);
        }
      }
      else {
        wx.showToast({
          image: '../../imgs/tips.png',
          title: '请选择产品规格',
        });
        return;
      }
    }
    selected_standardtypes.reverse();
    var url = '/index.php/api/Cart/AddCart';
    selected_standardtypes.sort(app.compare);
    var itemid = selected_standardtypes.join('_');
    if (itemid != '') {
      itemid = this.data.detailsinfo.spec_price[itemid].item_id;
    }
    var params = {
      goods_id: goodsid,
      item_id: itemid,
      goods_num: this.data.buycount
    };
    app.showLoading();
    app.request(url,params).then(this.addBuyCallBack.bind(this));
  },
  addBuyCallBack: function (result) {
    app.hideLoading();
    if (result.status.toString() == '1') {
      wx.showToast({
        icon: 'success',
        title: result.msg,
      });
    }
    else {
      wx.showToast({
        icon: 'none',
        title: result.msg,
      });
    }
    this.setData({
      dialogshow: false
    });
  },
  // 收藏商品
  collectGoods: function () {
    var url = '/index.php/api/Goods/collect_goods';
    var params = {
      goods_id: goodsid
    }
    app.request(url,params).then(this.collectCallBack.bind(this));
  },
  collectCallBack: function (result) {
    wx.showToast({
      icon: 'none',
      title: result.msg,
    });
  },
  // 图片预览
  showImage: function (event) {
    var curpic = event.currentTarget.dataset.curpic;
    var allpics = event.currentTarget.dataset.allpics;
    wx.previewImage({
      current: curpic,
      urls: allpics
    })
  }
})